package com.gph.saviorframework.auth.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.gph.saviorframework.auth.dao.AuthServiceDao;
import com.gph.saviorframework.auth.dao.AuthSystemDao;
import com.gph.saviorframework.auth.model.AuthService;
import com.gph.saviorframework.auth.model.AuthSystem;
import com.gph.saviorframework.auth.sec.rsa.RsaUtils;
import com.gph.saviorframework.auth.service.AuthCheckService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * Created by root on 16-7-21.
 */
public class AuthCheckServiceImpl implements AuthCheckService {

    @Autowired
    private AuthSystemDao authSystemDao;

    @Autowired
    private AuthServiceDao authServiceDao;

    /**
     * 校验授权
     *
     * @param token
     * @param name 系统名称
     * @param reqTime
     * @param service
     * @param sign
     * @return
     */
    public String checkAuth(String token, String name, String reqTime, String service, String sign) {

        JSONObject jsonObject = new JSONObject();

        try {
            //利用私钥解密sign信息
            //1 获取私钥匙
            AuthSystem authSystem = authSystemDao.getByName(name);
            if(authSystem==null){
                jsonObject.put("access","N");
            }
            else{
                String privateKey = authSystem.getPrivateKey();
                String sourceJsonStr = new String(RsaUtils.decryptByPrivateKey(sign.getBytes(),privateKey));
                JSONObject object = JSONObject.parseObject(sourceJsonStr);

                //2 判断相关信息
                if(object.getString("token").equals(token)&&object.getString("sysCode").equals(name)){
                    //判断service是否有权限
                    List<AuthService> serviceList = authServiceDao.findBySysId(name);

                    if(exist(serviceList, service)){
                        jsonObject.put("access","Y");
                    }
                    else{
                        jsonObject.put("access","N");
                    }
                }
                else{
                    jsonObject.put("access","N");
                }
            }
        }
        catch (Exception e){
            jsonObject.put("access","N");
        }
        return jsonObject.toJSONString();
    }

    private boolean exist(List<AuthService> authServices,String serviceName){
        for(AuthService authService : authServices){
            if(authService.getServiceName().equals(serviceName)){
                return true;
            }
        }
        return false;
    }
}
